/**
 * Description: 父子进程通信
 * File: fa_son.c |Time: 2021-04-06 14:53
 */

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int fd_f2s[2];
    int fd_s2f[2];
    
    if (pipe(fd_f2s) == -1) {
        perror("pipe f2s");
        return -1;
    }

    if (pipe(fd_s2f) == -1) {
        perror("pipe s2f");
        return -1;
    }


    pid_t pid = fork();

    if (pid == -1) {
        printf("fork error\n");
        return -1;
    }

    if (pid == 0) {
        close(fd_f2s[1]);
        char son_say[] = "I am your son.";
        int res = write(fd_s2f[1], son_say, strlen(son_say));

        if (res == -1) {
            printf("father write error.\n");
            return -1;
        }

        char buf[100] = {0};

        res = read(fd_f2s[0], buf, 100);
        printf("from father: %s\n", buf);
        memset(buf, 0, 100);
    } else {
        close(fd_s2f[1]);

        char father_say[] = "I am your father";
        int res = write(fd_f2s[1], father_say, strlen(father_say));

        if (res == -1) {
            printf("son write error.\n");
            return -1;
        }

        char buf[100] = {0};

            res = read(fd_s2f[0], buf, 100);
            printf("from son: %s\n", buf);
            memset(buf, 0, 100);
    }

    return 0;
}

